package com.tangly.codeing.service.impl;

import com.alibaba.fastjson.JSON;
import com.tangly.codeing.model.Article;
import com.tangly.codeing.repository.ArticleRepository;
import com.tangly.codeing.service.EsSearchService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * elasticsearch 搜索引擎 service实现
 *
 * @author tangbing
 * @date 2019/10/31
 */
@Service
public class EsSearchServiceImpl extends BaseSearchServiceImpl<Article> implements EsSearchService {

    private Logger log = LoggerFactory.getLogger(getClass());
    @Resource
    private ElasticsearchTemplate elasticsearchTemplate;
    @Resource
    private ArticleRepository articleRepository;

    @Override
    public void save(Article... articles) {
        elasticsearchTemplate.putMapping(Article.class);
        if (articles.length > 0) {
            /*Arrays.asList(productDocuments).parallelStream()
                    .map(productDocumentRepository::save)
                    .forEach(productDocument -> log.info("【保存数据】：{}", JSON.toJSONString(productDocument)));*/
            log.info("【保存索引】：{}", JSON.toJSONString(articleRepository.saveAll(Arrays.asList(articles))));
        }
    }

    @Override
    public void delete(String id) {
        articleRepository.deleteById(id);
    }

    @Override
    public void deleteAll() {
        articleRepository.deleteAll();
    }

    @Override
    public Article getById(String id) {
        return articleRepository.findById(id).get();
    }

    @Override
    public List<Article> getAll() {
        List<Article> list = new ArrayList<>();
        articleRepository.findAll().forEach(list::add);
        return list;
    }
}
